package com.penghaisoft.microwms.base.web.auth.service.impl;

import com.penghaisoft.microwms.base.web.auth.service.IBaseResourceService;
import com.penghaisoft.microwms.base.web.dictionary.dao.BaseDictionaryMapper;
import com.penghaisoft.microwms.base.web.resource.dao.BaseResourceMapper;
import com.penghaisoft.microwms.base.web.resource.dao.BaseUserResourceMapper;
import com.penghaisoft.microwms.base.web.resrole.dao.BaseResRoleMapper;
import com.penghaisoft.microwms.common.Constant;
import com.penghaisoft.microwms.common.base.model.BaseDictionary;
import com.penghaisoft.microwms.common.base.model.BaseResRole;
import com.penghaisoft.microwms.common.base.model.BaseResource;
import com.penghaisoft.microwms.common.dto.BaseResourceDto;
import com.penghaisoft.microwms.common.dto.BaseUserResourceForm;
import com.penghaisoft.microwms.common.dto.Resp;
import com.penghaisoft.microwms.common.page.Pager;
import com.penghaisoft.microwms.common.service.BaseService;
import com.penghaisoft.microwms.common.util.CommonUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 业务逻辑实现类
 * </p>
 *
 * @author
 * @createDate
 **/
@Service("baseResourceService")
public class BaseResourceServiceImpl extends BaseService implements IBaseResourceService {
	@Resource
	private BaseResourceMapper baseResourceMapper;
	
	@Resource
	private BaseResRoleMapper baseResRoleMapper;
	
	@Resource
	private BaseDictionaryMapper baseDictionaryMapper;

	@Autowired
	private BaseUserResourceMapper baseUserResourceMapper;

	/**
	 * 新增记录
	 * 
	 * @param baseResource
	 * @return
	 */
	@Override
	public Resp create(BaseResource baseResource) {
		baseResource.preQuery();
		baseResourceMapper.create(baseResource);
		return success();
	}

	/**
	 * 删除记录（逻辑删除）
	 * 
	 * @param baseResource
	 * @return
	 */
	@Override
	public Resp delete(BaseResource baseResource) {
		baseResourceMapper.delete(baseResource);
		return success();
	}

	/**
	 * 查询列表
	 * 
	 * @param page
	 * @param
	 * @return
	 */
	@Override
	public Pager<BaseResource> findListByCondition(int page, int rows, BaseResource condition) {
		Pager<BaseResource> pager = new Pager<>();
		pager.setPage(page);
		pager.setRows(rows);
		condition.preQuery();
		long size = baseResourceMapper.queryCount(condition);
		List<BaseResource> records = new ArrayList<BaseResource>();
		if(size > 0){
			records = baseResourceMapper.queryList(pager, condition);
		}
		pager.setRecords(records);
		pager.setTotalCount(size);
		return pager;
	}

	/**
	 * 查询单条
	 * 
	 * @param id
	 * @return
	 */
	@Override
	public BaseResource findById(String id) {
		return baseResourceMapper.queryById(id);
	}

	/**
	 * 修改记录
	 * 
	 * @param baseResource
	 * @return
	 */
	@Override
	public Resp update(BaseResource baseResource) {
		baseResourceMapper.updateBySelect(baseResource);
		return success();
	}

	/**
	 * 获取用户菜单
	 * 
	 * @return
	 */
	@Override
	public List<BaseResource> findMenuByLoginName(String loginName) {
		List<BaseResource> rootMenu = baseResourceMapper.findMenuByLoginName(loginName);
		// 最后的结果
		List<BaseResource> menuList = new ArrayList<BaseResource>();
		for (int i = 0; i < rootMenu.size(); i++) {
			if (CommonUtils.isBlank(rootMenu.get(i).getParentId())) {
				menuList.add(rootMenu.get(i));
			}
		}
		for (BaseResource menu : menuList) {
			menu.setChildResource(getResourceChild(menu.getResourceId(), rootMenu));
		}
		return menuList;
	}

	/**
	 * 根据用户查询拥有权限
	 * 
	 * @param loginName
	 * @return
	 */
	public List<String> findPermissionsByLoginName(String loginName) {
		return baseResourceMapper.findPermissionsByLoginName(loginName);
	}

	/**
	 * 查询所有权限
	 * 
	 * @return
	 */
	public List<BaseResource> findAllPermissions() {
		return baseResourceMapper.findAllPermissions();
	}

	/**
	 * 查询权限树
	 * 
	 * @return
	 */
	public List<BaseResourceDto> findResourceTree() {
		List<BaseResource> rootResource = baseResourceMapper.findAllResource();
		List<BaseResource> resourceList = new ArrayList<>();
		List<BaseResourceDto> resourceDtoList = new ArrayList<>();
		List<BaseDictionary> dicList = baseDictionaryMapper.queryAllByType(Constant.SYSTEM_DICTYPE);
		for (BaseDictionary baseDictionary : dicList){
			BaseResourceDto baseResourceDto = new BaseResourceDto();
			baseResourceDto.setResourceId(baseDictionary.getDicCode());
			baseResourceDto.setResourceName(baseDictionary.getDicName());
			resourceDtoList.add(baseResourceDto);
		}
		for (int i = 0; i < rootResource.size(); i++) {
			if (CommonUtils.isBlank(rootResource.get(i).getParentId())) {
				resourceList.add(rootResource.get(i));
			}
		}
		for (BaseResource baseResource : resourceList) {
			baseResource.setChildResource(getResourceChild(baseResource.getResourceId(), rootResource));
		}
		for (BaseResourceDto resourceDto : resourceDtoList){
			List<BaseResource> resources = new ArrayList<>();
			for (BaseResource baseResource : resourceList){
				if (resourceDto.getResourceId().equals(baseResource.getDicCode())) {
					resources.add(baseResource);
				}
			}
			resourceDto.setChildResource(resources);
		}
		return resourceDtoList;
	}

	/**
	 * 递归查询
	 * 
	 * @param id
	 * @param rootResource
	 * @return
	 */
	private List<BaseResource> getResourceChild(String id, List<BaseResource> rootResource) {
		List<BaseResource> childList = new ArrayList<>();
		for (BaseResource baseResource : rootResource) {
			if (!CommonUtils.isBlank(baseResource.getParentId())) {
				if (baseResource.getParentId().equals(id)) {
					childList.add(baseResource);
				}
			}
		}
		for (BaseResource baseResource : childList) {
			baseResource.setChildResource(getResourceChild(baseResource.getResourceId(), rootResource));
		}
		if (childList.isEmpty()) {
			return null;
		}
		return childList;
	}

	/**
	 * 查询单条
	 * 
	 * @param id
	 * @return
	 */
	@Override
	public BaseResource queryOneWithParent(String id) {
		return baseResourceMapper.queryOneWithParent(id);
	}

	/** 
	 * <p>Title: findHandPermissionsByLoginName</p> 
	 * <p>Description: 查找手持权限</p> 
	 * @Title: findHandPermissionsByLoginName 
	 * @Description: 查找手持权限
	 * @author zhangxu 
	 * @2017年6月6日:2017年6月6日:上午9:13:22
	 * @param @param loginName
	 * @param @return       
	 * @throws 
	 * @version V0.1 
	 */
	@Override
	public List<BaseResource> findHandPermissionsByUser(String userId) {
		return baseResourceMapper.findHandPermissionsByUser(userId);
	}

	@Override
	public List<BaseResource> findBtnByLoginName(String loginName) {
		List<BaseResource>  list = baseResourceMapper.findBtnByLoginName(loginName);
		return list;
	}

	/** 
	 * 根据用户名和工厂查询用户在某工厂下的资源
	 */
	@Override
	public List<BaseResource> findMenuByLoginNameAndFactory(String loginName, String factoryCode) {
		
//		1. 先找到用户的角色
		List<BaseResRole> roles = baseResRoleMapper.queryUserResRole(loginName);
//		用户拥有的角色
		List<String> roleIds = new ArrayList<>();
		for (BaseResRole baseResRole : roles) {
			String roleType = baseResRole.getResreoleType();
			String roleId = baseResRole.getResroleId();
//			通用角色
			if ("0".equals(roleType)) {
				roleIds.add(roleId);
			}
//			工厂角色
			if("1".equals(roleType)) {
//				查询当前工厂有没有这个角色
				int count = baseResRoleMapper.queryRoleUnderFactory(roleId,factoryCode);
				if (count > 0) {
					roleIds.add(roleId);
				}
			}
		}
		
		List<BaseResource> menuAll = new ArrayList<BaseResource>();
		List<BaseResource> menuList = new ArrayList<BaseResource>();
//		2  通用角色获取资源
		if (roleIds.size() > 0) {
			menuAll = baseResourceMapper.queryResUnderRoles(roleIds);
			// 最后的结果
			for (int i = 0; i < menuAll.size(); i++) {
				if (CommonUtils.isBlank(menuAll.get(i).getParentId())) {
					menuList.add(menuAll.get(i));
				}
			}
			for (BaseResource menu : menuList) {
				menu.setChildResource(getResourceChild(menu.getResourceId(), menuAll));
			}
		}
		
		return menuList;
	}

	/** 
	 * @Description: 查询用户的角色
	 * @Param:  
	 * @return:  
	 * @Author: zhangx
	 * @Date: 2018/4/26 16:03
	 */ 
	@Override
	public Pager<BaseUserResourceForm> findUserResList(int page, int rows, BaseUserResourceForm condition) {
		Pager<BaseUserResourceForm> pager = new Pager<BaseUserResourceForm>();
		pager.setPage(page);
		pager.setRows(rows);
		List<BaseUserResourceForm> records = baseUserResourceMapper.queryFormList(pager,condition);
		long size = baseUserResourceMapper.queryFormCount(condition);
		pager.setRecords(records);
		pager.setTotalCount(size);
		return pager;
	}
}
